// Copyright (c) 2012 SameGoal LLC.
// All Rights Reserved.
// Author: Andy Hochhaus <ahochhaus@samegoal.com>

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NET_HTTP_SERVER_EVENT_REQUEST_H_
#define NET_HTTP_SERVER_EVENT_REQUEST_H_

#include <event2/event.h>
#include <event2/listener.h>
#include <gflags/gflags.h>
#include <glog/logging.h>

#include <utility>
#include <string>
#include <vector>

#include "base/basictypes.h"
#include "net/http/server/event/event_server.h"
#include "third_party/zlib/gzip.h"
#include "util/worker_pool/worker_pool.h"

namespace sg {
namespace net {
namespace http {
namespace server {
namespace event {

namespace zlib = ::sg::third_party::zlib;

class Connection;

enum HttpStatus {
  OK = 200,
  MOVED_PERMANENTLY = 301,
  FOUND = 302,
  NOT_FOUND = 404,
  INTERNAL_SERVER_ERROR = 500,
};

class Request {
 public:
  explicit Request(Connection *conn);
  ~Request();

  // parsing interface (used by Connection class)
  bool AddHeader(const std::string &str);
  void AppendBody(const std::string &str, const bool body_done);
  bool IsReadingHeaders();
  bool IsReadingBody();
  bool IsReadingDone();
  bool IsFinished();

  // used by http redirect
  bool IsEncrypted();

  // application level callback interface
  enum RequestType { GET, HEAD, POST };
  enum RequestVersion { ONE, ONE_ONE, SPDY };
  typedef std::pair<std::string, std::string> KeyValuePair;
  typedef std::vector<KeyValuePair *> OrderedKeyValuePairs;

  std::string address();
  uint16 port();
  RequestType request_type();
  std::string request_uri();
  std::string request_path();
  std::string request_query();
  std::string request_body();
  RequestVersion request_version();

  bool GetQueryParam(const std::string &key, std::string *value);
  bool GetQueryParamAsInt64(const std::string &key, int64 *value);
  bool GetQueryParamAsUint64(const std::string &key, uint64 *value);
  OrderedKeyValuePairs GetQueryParamQueue();
  bool GetHeader(const std::string &key, std::string *value);
  bool GetHeaderAsInt64(const std::string &key, int64 *value);
  bool GetHeaderAsUint64(const std::string &key, uint64 *value);
  OrderedKeyValuePairs GetHeaderQueue();
  bool GetPost(const std::string &key, std::string *value);
  bool GetPostAsInt64(const std::string &key, int64 *value);
  bool GetPostAsUint64(const std::string &key, uint64 *value);
  OrderedKeyValuePairs GetPostQueue();
  void GetOutput(std::string *output);
  std::string GetRawRequest();

  void AddResponseHeader(const std::string &key, const std::string &value);
  void AddResponseHeader(const std::string &key, const int64 value);
  bool GetResponseHeader(const std::string &key, std::string *value);

  void AddDefaultResponseHeaders();
  void AddCacheableResponseHeaders();
  void AddNonCacheableResponseHeaders();

  void StartChunk(const HttpStatus code);
  void SendChunk(const std::string &body);
  void EndChunk(const std::string &body);
  void Send(const HttpStatus code, const std::string &body);
  void SendError(const HttpStatus code, const std::string &error);
  void SendRaw(const std::string &response_str);
  void CloseConnectionAfterNextWrite();
  Connection *connection();

 private:
  Connection *conn_;
  zlib::GzipStream *gzip_stream_;
  bool browser_supports_gzip_;

  enum RequestState { REQUEST, HEADERS, BODY, RESPONSE, FINISHED };
  std::vector<std::string> raw_request_;
  RequestState request_state_;
  RequestType request_type_;
  std::string request_uri_, request_path_, request_query_, request_body_;
  RequestVersion request_version_;
  OrderedKeyValuePairs query_params_, headers_, post_, response_headers_;
  bool post_parsed_;
  std::vector<std::string> output_buffer_;

  static bool ParseRequestType(const std::string &type_str, RequestType *type);
  static bool ParseRequestVersion(const std::string &version_str,
                                  RequestVersion *version);
  void EnsurePostParsed();
  static void ParseQueryString(const std::string &query_str,
                               OrderedKeyValuePairs *queue);
  static void ParseMultiPart(const std::string &query_str,
                             const std::string &boundary,
                             OrderedKeyValuePairs *queue);
  static void UnescapeQueryPiece(std::string *piece);
  static bool GetFirstValue(const std::string &key,
                            OrderedKeyValuePairs *queue,
                            std::string *value);
  static bool GetFirstValueAsInt64(const std::string &key,
                                   OrderedKeyValuePairs *queue,
                                   int64 *value);
  static bool GetFirstValueAsUint64(const std::string &key,
                                    OrderedKeyValuePairs *queue,
                                    uint64 *value);
  static void NormalizeHttpHeader(std::string *key);

  void OutputHeaders(const HttpStatus code);
  static std::string StatusString(const HttpStatus code);

  void InitGzipStream();

  DISALLOW_COPY_AND_ASSIGN(Request);
};

}  // namespace event
}  // namespace server
}  // namespace http
}  // namespace net
}  // namespace sg

#endif  // NET_HTTP_SERVER_EVENT_REQUEST_H_
